package spring.aop.advice;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * description: 使用普通方式进行事务的添加
 * 1. 对比 TxAroundAdvice 通过环绕方式添加
 * 2. 指定一个优先级的值, 值越小，优先级越高! 越高的前置先执行,后置后执行 @Order(10)
 */
@Component
@Aspect
@Order(10)
public class TxAdvice {

    @Before("spring.aop.pointcut.MyPointCut.pc()")
    public void begin(JoinPoint joinPoint){
        System.out.println("MethodName = " + joinPoint.getSignature().getName());
        System.out.println("TxAdvice @Before 开启事务");
    }

    @AfterReturning(value = "spring.aop.pointcut.MyPointCut.pc()", returning = "result")
    public void commit(Object result){
        // 获取方法执行结果
        System.out.println("TxAdvice result = " + result.toString());
        System.out.println("TxAdvice @AfterReturning 事务提交");
    }

    @AfterThrowing(value = "spring.aop.pointcut.MyPointCut.pc()", throwing = "t")
    public void rollback(JoinPoint joinPoint, Throwable t){
        // 获取方法抛出的异常
        System.out.println("TxAdvice Throwable = " + t);
        // 除0时异常：TxAdvice Throwable = java.lang.ArithmeticException: / by zero
        System.out.println("TxAdvice @AfterThrowing 事务回滚");
    }

    @After("spring.aop.pointcut.MyPointCut.pc()")
    public void afterMethod() {
        System.out.println("TxAdvice @After 全部运行完毕");
    }

}
